package com.zxq.common.utils.json;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;

public class GsonTool implements IGson {

    private static final Gson GSON = new GsonBuilder().setDateFormat(STANDARD_PATTERN).create();

    private static GsonTool gsonTool = new GsonTool();

    private GsonTool() {

    }

    public static GsonTool getInstance() {
        return gsonTool;
    }

    @Override
    public String toJson(Object obj) {
        try {
            return GSON.toJson(obj);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public <T> T toObject(String json, Class<T> clazz) {
        return GSON.fromJson(json, clazz);
    }


    @Override
    public <T> T toObject(String json, TypeToken<?> valueTypeRef) {
        try {
            Type type = valueTypeRef.getType();
            return (T) GSON.fromJson(json, type);
        } catch (Exception e) {
            throw e;
        }
    }

    @Override
    public Map<String, Object> convertToMap(Object fromValue) {
        try {
            JsonElement jsonElement = GSON.toJsonTree(fromValue);
            return GSON.fromJson(jsonElement, new TypeToken<Map<String, Object>>() {
            }.getType());
        } catch (Exception e) {
            throw e;
        }
    }

    @Override
    public Map<String, Object> convertToMap(String json) {
        return GSON.fromJson(json, new TypeToken<Map<String, Object>>() {
        }.getType());
    }

    @Override
    public <T> T toObject(byte[] result, Class<T> clazz) {
        try {
            JsonElement jsonElement = GSON.toJsonTree(result);
            return GSON.fromJson(jsonElement, new TypeToken<T>() {
            }.getType());
        } catch (Exception e) {
            throw e;
        }
    }

    @Override
    public <T> List<T> toList(String json, Class<T> clazz) {
        try {
            return GSON.fromJson(json, TypeToken.getParameterized(List.class, clazz).getType());
        } catch (Exception e) {
            throw e;
        }
    }

}

